import { list } from "postcss"
import { reqgetcate, reqgetgoods } from "../../http/api"
const initState = {
    //获取商品分类
    list: [],
    n: 1,
    //获取商品分类
    goods: [],
    pre: "http://localhost:1000",


}

const types = {
    //修改types
    CHANGE_CATE: "CHANGE_CATE",
    //修改n
    CHANGE_N: "CHANGE_N",
    //修改goods
    CHANGE_GOODS: "CHANGE_GOODS"
}

const reducer = (state = initState, action) => {
    //修改cate
    switch (action.type) {
        //修改cate
        case types.CHANGE_CATE:
            return {
                ...state,
                list: action.list
            }
        //修改n
        case types.CHANGE_N:
            return {
                ...state,
                n: action.n
            }
        //修改goods
        case types.CHANGE_GOODS:
            return {
                ...state,
                goods: action.goods
            }
        default:
            return state
    }
}

export const actions = {
    //修改cate
    changeList: list => ({ type: types.CHANGE_CATE, list }),
    //修改n
    changeN: n => ({ type: types.CHANGE_N, n }),
    //修改goods
    changeGoods: goods => ({ type: types.CHANGE_GOODS, goods }),

    changeNum:(e)=>(dispatch,getState)=>{
        dispatch(actions.changeN(e))
        dispatch(actions.reqGoods(e))
    },

    //获取cate
    reqCate: () => (dispatch, getState) => {
        reqgetcate().then(res => {
            if (res.data.code == 200) {
                dispatch(actions.changeList(res.data.list))
            }
        })
    },

    //请求goods
    reqGoods: (e) => (dispatch, getState) => {
        let goods = getGoods(getState())
        if (goods.length > 0) {
            return;
        }
        let fid = getCateN(getState())
        reqgetgoods({ fid }).then(res => {
            // console.log(res);
            if (res.data.code == 200) {
                dispatch(actions.changeGoods(res.data.list))
            }
            
        })
    },


}

export const getList = state => state.cate.list
export const getCateN = state => state.cate.n
export const getGoods = state => state.cate.goods
export const getPre = state => state.cate.pre

export default reducer;